/**
 * Copyright 2011 FeedDreamwork SIG
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.feeddreamwork.fetcher;

import java.util.*;

import javax.jdo.*;

import org.feeddreamwork.*;

public class PageInfoRepository extends RepositoryBase {
	public PageInfo getPageInfo(String url) {
		Utils.throwIfNullOrEmpty(url);

		return (PageInfo) this.tryGetObjectById(PageInfo.class, url);
	}

	public boolean addPageInfo(String url) {
		Utils.throwIfNullOrEmpty(url);

		PageInfo pageInfo = new PageInfo(url);

		Transaction tx = this.persistenceManager.currentTransaction();
		try {
			tx.begin();
			if (tryGetObjectById(PageInfo.class, url) == null) {
				this.persistenceManager.makePersistent(pageInfo);
				tx.commit();
				return true;
			} else {
				tx.commit();
				return false;
			}
		} catch (ConcurrentModificationException e) {
			return false;
		} finally {
			if (tx.isActive())
				tx.rollback();
		}
	}

	public List<PageInfo> getPageInfos() {
		String query = "select from " + PageInfo.class.getName() + " order by addTime desc";
		@SuppressWarnings("unchecked")
		List<PageInfo> results = (List<PageInfo>) this.persistenceManager.newQuery(query).execute();
		return results;
	}

	public void clearFinished(int deleteDaysBefore) {
		Utils.throwIfSmallerThan(deleteDaysBefore, 0);

		Calendar deleteBefore = Calendar.getInstance();
		deleteBefore.add(Calendar.DATE, -deleteDaysBefore);

		String query = "select from "
				+ PageInfo.class.getName() + " where addTime <= timeParam parameters java.util.Date timeParam";
		@SuppressWarnings("unchecked")
		List<PageInfo> results = (List<PageInfo>) this.persistenceManager.newQuery(query).execute(deleteBefore.getTime());
		this.persistenceManager.deletePersistentAll(results);
	}
}
